package com.cafe.case4;

import java.util.concurrent.*;

public class VirtualThreadDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //方法1、通过Thread.startVirtualThread创建线程
        Thread t1 = Thread.startVirtualThread(new CafeRunnable());
        t1.join();

        //方法2、通过Thread.ofVirtual()创建虚拟线程
        Thread t2 = Thread.ofVirtual().name("虚拟线程-CAFE2").start(new CafeRunnable());
        Thread t3 = Thread.ofVirtual().name("虚拟线程-CAFE3").unstarted(new CafeRunnable());
        t2.join();
        t3.start();
        t3.join();

        Thread.ofPlatform().name("物理线程-CAFE1").start(new CafeRunnable());


        //方法3、通过Thread.ofVirtual().factory()创建虚拟线程
        ThreadFactory factory = Thread.ofVirtual().factory();
        Thread t4 = factory.newThread(new CafeRunnable());
        t4.setName("虚拟线程-CAFE4");
        t4.start();
        t4.join();

        //方法4、Executors.newVirtualThreadPerTaskExecutor()创建线程
        try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
            Future<?> f1 = executorService.submit(new CafeCallable(10));
            Future<?> f2 = executorService.submit(new CafeCallable(20));
            Future<?> f3 = executorService.submit(new CafeCallable(30));
            System.out.println(f1.get());
            System.out.println(f2.get());
            System.out.println(f3.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
   